package com.tanhua.dubbo.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.domain.mongodb.Movement;
import com.tanhua.model.domain.mongodb.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author maorf
 * @version 1.0
 */
@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void save(Movement movement) {
        //设置pid
        Long pid = idWorker.getNextId("movement");
        movement.setPid(pid);
        movement.setCreated(System.currentTimeMillis());
        movement.setTopState(1);
        mongoTemplate.save(movement);
        timeLineService.saveTimeLine(movement);
    }

    @Override
    public PageResult findMovementsById(Long userId, Integer page, Integer pagesize) {
        Pageable pageable = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")));
        Criteria criteria = Criteria.where("friendId").is(userId);
        Query query = Query.query(criteria).with(pageable);
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementIds = new ArrayList<>();
        for (MovementTimeLine timeLine : timeLines) {
            movementIds.add(timeLine.getMovementId());
        }
        List<Movement> movements = mongoTemplate.find(Query.query(Criteria.where("id").in(movementIds)), Movement.class);
        return new PageResult(page, pagesize, movements.size(), movements);
    }

    @Override
    public PageResult findRecommendMovementsById(Long userId, Integer page, Integer pagesize) {
        String s = redisTemplate.opsForValue().get("MOVEMENTS_RECOMMEND_" + userId);
        if (StringUtils.isEmpty(s)) {
            //随机推荐10条
            TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                    Aggregation.sample(pagesize));

            AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);

            List<Movement> mappedResults = movements.getMappedResults();
            List<Movement> collect = mappedResults.stream().filter((item) -> {
                return item.getUserId() != userId;
            }).filter((item) -> {
                return item.getState() == 5;
            }).collect(Collectors.toList());
            if (ObjectUtil.isEmpty(collect)) {
                movements = mongoTemplate.aggregate(aggregation, Movement.class);

                mappedResults = movements.getMappedResults();
                collect = mappedResults.stream().filter((item) -> {
                    return item.getUserId() != userId;
                }).filter((item) -> {
                    return item.getState() == 5;
                }).collect(Collectors.toList());
            }
            return new PageResult(page, pagesize, collect.size(), collect);
        } else {
            String[] split = s.split(",");
            List<Long> list = new ArrayList<>();
            for (String s1 : split) {
                list.add(Long.valueOf(s1));
            }
            Pageable pageable = PageRequest.of(page - 1, pagesize);
            Query query = Query.query(Criteria.where("pid").in(list).and("state").is(5)).with(pageable);
            List<Movement> movements = mongoTemplate.find(query, Movement.class);
            return new PageResult(page, pagesize, movements.size(), movements);
        }

    }

    @Override
    public PageResult FindOwnMovementsById(Long userId, Integer page, Integer pagesize) {
        Pageable pageable = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created"), Sort.Order.desc("topState")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageable).with(Sort.by(Sort.Order.desc("topState")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, movements.size(), movements);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }
}
